package testLayer;

import static org.junit.Assert.*;
import dbLayer.DBConnection;
import dbLayer.DBSalesOrder;
import modelLayer.SalesOrder;
import modelLayer.Customer;

import java.sql.*;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class DBSalesOrderTest {
	
	private Connection   con;
	private DBSalesOrder dbSalesOrder;
	private SalesOrder   salesOrder = new SalesOrder();
	private Customer     customer = new Customer(1, "Peter Jensen", "Vibevej 12" ,"what ever" , "Danmark", "98124565" , "p@mail.dk", 9000);
	
	private String buildQuery(String wClause) {
		
		String query = "SELECT date, deliveryStatus, deliveryDate, customerID, invoiceID FROM SalesOrder";
		if (wClause.length() > 0)
			query = query + " where " + wClause;
		return query;
		
	}
	
	/**
	 * The singleWhere is used to execute queries in the database salesOrder
	 */
	private SalesOrder singleWhere(String wClause) {
		

		SalesOrder salesOrder = new SalesOrder();

		try {
			String query = buildQuery(wClause);
			Statement stmt = this.con.createStatement();
			stmt.setQueryTimeout(5);
			ResultSet results = stmt.executeQuery(query);
			stmt.close();
		}
 		catch(Exception e) {
	 		System.out.println("Query exception: " + e);
 		}
		return salesOrder;
		
	}
	
	/**
	 * The doRemove is used to clear the sales database 
	 */
	private void doRemoveTestTubles() {
		
		String wClause = "DELETE FROM salesOrder where deliveryStatus like '%TEST%'";
		try {
			Statement stmt = this.con.createStatement();
			stmt.setQueryTimeout(5);
			stmt.executeQuery(wClause);
			stmt.close();
		}
		catch(SQLException e) {
	 		System.out.println("Query exception: " + e);
		}
		
	}
	
	@Before
	public void setUp() throws Exception {
		
		this.con = DBConnection.getInstance().getDBcon();
		this.dbSalesOrder = new DBSalesOrder();
		
	}

	@After
	public void tearDown() throws Exception {
		
		
		
	}

	/**
	 * First we set the deliveryStatus to 'TEST' so that we can search for that later
	 * Then we add the customer to the salesOrder so that DBSalesOrder can insert the 
	 * sales order into the database
	 * In the end we 
	 */
	@Test
	public void testInsertOrder() throws Exception {
		
		this.salesOrder.setDeliveryStatus("TEST");
		this.salesOrder.setCustomer(customer);
		doRemoveTestTubles();
		this.dbSalesOrder.insertOrder(this.salesOrder);
		String wClause = "DeliveryStatus like '%TEST%'";
		assertTrue(singleWhere(wClause) != null);
		
	}
	
}
